package com.seednia.foundation.framework.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * String manipulation utility class
 * @author Young Suk Ahn
 *
 */

public class StringUtils 
{
	
	public static final boolean isNullOrEmpty(String val)
	{
		if (val == null || val.trim().length() == 0)
			return true;
		return false;
	}

	/**
	 * Parses a text of form
	 * key1=val&key2=val2...
	 * @param query
	 * @return
	 */
	public static final Map<String, Object> getQueryMap(String query)  
	{  
	    String[] params = query.split("&");  
	    Map<String, Object> map = new HashMap<String, Object>();  
	    for (String param : params)  
	    {  
	    	String[] tokens = param.split("=");
	        String name = tokens[0];  
	        String value = tokens[1];  
	        map.put(name, value);  
	    }  
	    return map;  
	}  
	
	/**
	 * Does the opposite of getQueryMap
	 * @param map
	 * @return
	 */
	public static final String getQueryString(Map<String, Object> map)  
	{  
		if (map == null)
			return null;
		
	    StringBuffer retval = new StringBuffer();

	    int ctr = 0;
	    for (Map.Entry<String, Object> entry : map.entrySet()) {
	    	if (ctr > 0)
	    		retval.append("&");
	    	retval.append(entry.getKey()).append("=").append(entry.getValue().toString());
	    	ctr++;
	    }
	    
	    return retval.toString();  
	}  
	
	
	public static String inputStreamToString(InputStream is, String charset) throws IOException {
		/*
		 * To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String.
		 */
		if (is != null) {
			StringBuilder sb = new StringBuilder();
			String line;

			if (charset == null)
				charset = "UTF-8";
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
				}
			} finally {
				is.close();
			}
			return sb.toString();
		} else {       
			return "";
		}
	}

	public static InputStream stringToInputStream(String arg, String charset) {
		InputStream retval = null;
		if (charset == null)
			charset = "UTF-8";
		/*
		 * Convert String to InputString using ByteArrayInputStream class.
		 * This class constructor takes the string byte array which can be
		 * done by calling the getBytes() method.
		 */
		try {
			retval = new ByteArrayInputStream(arg.getBytes(charset));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return retval;
	}
}
